<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useItemStore } from '../stores/songye' // 导入 Pinia store
import { gethone, gethonenr, gethonenr2 } from '../api/index'

const store = useItemStore() // 使用 Pinia store

const router = useRouter()

const navigateToLivePlayback = (item: any) => {
  store.setItemIdUrl(item.itemIdUrl)
  store.setActorIdUrl(item.actorIdUrl) // 将 itemIdUrl 存储到 Pinia 中
  router.push({
    path: '/LivePlayback', // 路由路径
  })
}

const doSearchWithHistory = (searchTerm: string) => {
  router.push({
    name: 'SearchResult',
    query: {
      q: searchTerm,
    },
  })
}

const navigateToSearch = () => {
  router.push('/shop')
}

// 数据及状态
const items = ref<any[]>([])
const displayedItems = ref<any[]>([])
const firstFrames = ref<any[]>([])
const firstFrames2 = ref<any[]>([])
const currentPage = ref(1) // 当前页码
const isLoading = ref(true)

const loadingState = ref({
  items: true,
  firstFrames: true,
  firstFrames2: true,
  isLoadingNextPage: false, // 是否正在加载下一页
})

const fetchData = async () => {
  try {
    // 并行请求
    const [homeData, firstGroupData, secondGroupData] = await Promise.all([
      gethone(),
      gethonenr(currentPage.value),
      gethonenr2(currentPage.value + 1),
    ])

    items.value = homeData.data
    displayedItems.value = items.value.slice(0, 10)
    firstFrames.value = firstGroupData.data.data.list
    firstFrames2.value = secondGroupData.data.data.list
  } catch (error) {
    console.error('数据加载失败:', error)
  } finally {
    loadingState.value.items = false
    loadingState.value.firstFrames = false
    loadingState.value.firstFrames2 = false
  }
}

const loadNextPage = async () => {
  if (loadingState.value.isLoadingNextPage) return // 避免重复加载
  loadingState.value.isLoadingNextPage = true

  try {
    currentPage.value += 2 // 偶数页+2
    const nextFrames1 = await gethonenr(currentPage.value - 1) // 奇数页
    const nextFrames2 = await gethonenr2(currentPage.value) // 偶数页

    firstFrames.value = [...firstFrames.value, ...nextFrames1.data.data.list]
    firstFrames2.value = [...firstFrames2.value, ...nextFrames2.data.data.list]
  } catch (error) {
    console.error('加载下一页失败:', error)
  } finally {
    loadingState.value.isLoadingNextPage = false
  }
}

const handleScroll = () => {
  const { scrollTop, scrollHeight, clientHeight } = document.documentElement
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    loadNextPage()
  }
}

onMounted(async () => {
  // isLoading.value = true // 开始加载数据时，设置 isLoading 为 true
   setTimeout(() => {
      isLoading.value = false; // 数据加载完成后，设置为 false
    }, 3000);  // 假设数据加载有延迟，可以根据实际情况调整
  
  try {
    await fetchData() // 获取数据
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    isLoading.value = false // 数据加载完成后，设置 isLoading 为 false
  }

  window.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<template>
  <div class="wl">

    <div v-if="isLoading" class="loading-container">
      <!-- 使用 Vant Loading 组件 -->
      <van-loading type="spinner" size="24px" text="加载中..." color="#1e1e1e" />
    </div>
    
    <!-- 搜索框 Header -->
    <header class="search-header">
      <nav class="songs">
        <div class="fenl">
          <router-link to="/fenglei">
            <img src="../../public/images/分类.png" alt="" />
          </router-link>
        </div>
        <van-search class="guanjian" placeholder="请输入搜索关键词" @click="navigateToSearch" />
        <div class="liaot">
          
          <RouterLink to="/liaotian"><img src="../../public/images/聊天.png" alt="" /></RouterLink>

        </div>
      </nav>
    </header>


    <!-- 骨架屏 -->
    <div
      v-if="loadingState.items || loadingState.firstFrames || loadingState.firstFrames2"
      class="gujia"
    >
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
      <van-skeleton class="gujia2" title avatar :row="1" />
    </div>

    


    <!-- 显示切片数据 -->
    <div class="lel3" v-else>
      <div
        class="lel"
        v-for="(item, index) in displayedItems"
        :key="index"
        @click="doSearchWithHistory(item.title)"
      >
        <img :src="item.image" alt="" />
        <div>{{ item.title }}</div>
      </div>
    </div>

    <div class="op">
      <div class="nr1">
        <div
          class="lel2"
          v-for="(item, index) in firstFrames"
          :key="index"
          @click="navigateToLivePlayback(item)"
        >
          <div class="shopbankuai">
            <div class="image-container">
              <!-- <img v-lazy="item.itemImage" alt="first-frame" class="first-frame" /> -->
              <van-image
                :src="item.itemImage"
                alt="first-frame"
                class="first-frame"
                fit="cover"
                height="200rem"
            
              />

              <div class="toxing2">
                <div>
                  <img :src="item.actorAvatar" alt="" />
                  <span class="tozi3">{{ item.actorName }}</span>
                  <div class="tozi4">{{ item.actorTag }}</div>
                </div>
              </div>
            </div>

            <div class="zit">{{ item.title }}</div>
            <div class="zit1">
              ￥{{ item.showDiscountPrice }}
              <img
                src="https://s10.mogucdn.com/mlcdn/c45406/200928_043cgf54cjia5d88gfj5j626id541_66x36.png"
                class="baoyou"
              />
              <div class="xiaoliang">{{ item.sale }}</div>

              <div v-for="(tag, tagIndex) in item.lefttop_taglist" :key="tagIndex">
                <!-- 显示 img -->
                <div class="yier">
                  <img :src="tag.img" />
                </div>
                <div class="zhanting1">
                  <img src="../../public/images/暂停mogu.png" alt="" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 第二组图片 -->
      <div class="nr2">
        <div
          class="lee2"
          v-for="(item, index) in firstFrames2"
          :key="index"
          @click="navigateToLivePlayback(item)"
        >
          <div class="shopbankuai">
            <div class="image-container">
              <!-- <img v-lazy="item.itemImage" alt="first-frame" class="first-frame" /> -->
              <van-image
                :src="item.itemImage"
                alt="first-frame"
                class="first-frame"
                fit="cover"
                height="200rem"
              
              />

              <div class="toxing2">
                <div>
                  <img :src="item.actorAvatar" alt="" />
                  <span class="tozi3">{{ item.actorName }}</span>
                  <div class="tozi4">{{ item.actorTag }}</div>
                </div>
              </div>
            </div>

            <div class="zit">{{ item.title }}</div>
            <div class="zit1">
              ￥{{ item.showDiscountPrice }}
              <img
                src="https://s10.mogucdn.com/mlcdn/c45406/200928_043cgf54cjia5d88gfj5j626id541_66x36.png"
                class="baoyou"
              />
              <div class="xiaoliang">{{ item.sale }}</div>

              <div v-for="(tag, tagIndex) in item.lefttop_taglist" :key="tagIndex">
                <!-- 显示 img -->
                <div class="yier">
                  <img :src="tag.img" />
                </div>
                <div class="zhanting1">
                  <img src="../../public/images/暂停mogu.png" alt="" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 锚点 -->
      <div class="showmore">
        <div v-if="!loadingState.isLoadingNextPage" @click="loadNextPage">
          <img src="../../public/images/下拉刷新.png" alt="" />
        </div>
        <div v-else>
          <img src="../../public/images/刷新中.jpg" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>


<style lang="less" scoped>
.tongxingzi2 {
  position: absolute;
  font-size: 12rem;
  left: 50rem;
  top: 1rem;
}
.tozi3 {
  position: absolute;
  font-size: 13rem;
  color: #fff;
  top: 3rem;
  left: 30rem;
}
.tozi4 {
  width: 31%;
  position: absolute;
  font-size: 8rem;
  color: #fff;
  top: 7rem;
  left: 100rem;
  margin: 0 auto;
  background-color: #00000069;
  white-space: nowrap; /* 强制文本不换行 */
  overflow: hidden; /* 隐藏超出容器的文本 */
  text-overflow: ellipsis; /* 显示省略号 */
}
.image-container {
  position: relative; /* 头像定位以此为基准 */
}
.toxing2 {
  position: absolute;
  top: 90%;
  left: 37%;
  transform: translate(-50%, -50%);

  height: auto;
  img {
    width: 22%;
    border-radius: 50%;
  }
}
.zhanting1 {
  position: absolute;
  width: 28rem;
  top: 4rem;
  left: 138rem;
  img {
    width: 100%;
  }
}
.yier {
  position: absolute;
  width: 48rem;
  top: 9rem;

  width: 48rem;
  img {
    width: 100%;
  }
}
.wl {
  width: 100%;
  border-bottom: 1px solid #e5e5e5;
}

.lel3 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.lel {
  width: 20%;
  display: flex;
  align-items: center;
  flex-direction: column;
  font-size: 12rem;
  color: #696868;
  margin-bottom: 3rem;
  margin-top: 9rem;

  img {
    width: 40rem;
    height: 40rem;
  }

  .first-frame {
    width: 10rem;
    height: 10rem;
    margin-top: 10rem;
    border-radius: 50%;
  }
}

.gujia {
  margin-top: 20rem;
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
}

.first-frame {
  width: 100%;
}

.sonyenr {
  width: 100%;
  display: flex;
}

.lel2 {
  width: 90%;
}

.zit {
  font-size: 13rem;
  margin: 8rem auto;
  width: 90%;
}

.lee2 {
  width: 90%;
}

.search-header {
  background-color: #fff;
  border-bottom: 1rem solid #e5e5e5;
}

.songs {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  padding: 10rem;
}

.fenl {
  width: 34rem;
  display: flex;
  align-items: center;

  img {
    width: 22rem;
  }
}

.liaot {
  img {
    width: 25rem;
  }
}

.guanjian {
  color: #eeeeee;
  width: 83%;
  height: 21rem;
}

.nr1 {
  display: flex;
  width: 50%;
  flex-direction: column;
  align-items: center;
  margin-left: 5rem;
}

.nr2 {
  width: 50%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-right: 5rem;
}

.op {
  display: flex;
  margin-top: 13rem;
  background-color: whitesmoke;
}

.zit1 {
  font-size: 15rem;
  color: #f46;
  width: 95%;
  padding-bottom: 5rem;
  margin: 0 auto;

  .xiaoliang {
    float: right;
    font-size: 10rem;
    background: rgba(255, 68, 102, 0.263);
    border-radius: 10rem;
    padding: 1rem 5rem;
    margin-right: 5rem;
  }
}

.baoyou {
  width: 23rem;
  height: auto;
  margin-left: 3rem;
}

.shopbankuai {
  margin-top: 14rem;
  border-radius: 5rem;
  background: white;
  position: relative;

  .first-frame {
    width: 100%;
    height: auto;
    border-top-right-radius: 5rem;
    border-top-left-radius: 5rem;
  }
}
.gujia2 {
  margin-left: 10rem;
  width: 9%;
}
.loading-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);  /* 背景透明效果 */
  z-index: 999;
}
</style>
